﻿using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Restful_Api.Helpers
{
    /// <summary>
    /// 动态的属性 多个资源的数据塑性
    /// </summary>
    public static class IEnumerableExtensions
    {
        public static IEnumerable<ExpandoObject> ShapeDate<TSource>(this IEnumerable<TSource> sources, string fields)
        {
            if (sources == null)
                throw new ArgumentNullException(nameof(sources));

            var expandoObjectList = new List<ExpandoObject>(sources.Count());
            var propertyInfoList = new List<PropertyInfo>();

            if (string.IsNullOrWhiteSpace(fields))
            {
                var properInfos = typeof(TSource)
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance);
                propertyInfoList.AddRange(properInfos);
            }
            else
            {
                var fieldsAfterSplit = fields.Split(',');
                foreach (var item in fieldsAfterSplit)
                {
                    var propertyName = item.Trim();
                    var propertyInfo = typeof(TSource)
                        .GetProperty(propertyName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);
                    if (propertyInfo == null)
                        throw new Exception($"Property:{propertyName}没有找到");

                    propertyInfoList.Add(propertyInfo);
                }
            }
            foreach (var obj in sources)
            {
                var shapedObj = new ExpandoObject();
                foreach (var item in propertyInfoList)
                {
                    var proertyValue = item.GetValue(obj);
                    ((IDictionary<string, object>)shapedObj).Add(item.Name, proertyValue);
                }
                expandoObjectList.Add(shapedObj);
            }
            return expandoObjectList;
        }
    }
}
